<?php

namespace app\api\controller;

use app\api\logic\UserLogic;
use app\api\validate\SetWechatUserValidate;
use app\api\validate\UpdateUserValidate;
use think\admin\Controller;
use think\exception\ValidateException;
use think\Request;
use think\response\Json;

/**
 * Class User
 * @package app\api\controller
 */
class User extends Controller
{

    private $default_type = 'json';
    protected $middleware = ['check'];
    private $userModel;
    public $request;
    public function __construct(Request $request){
        $this->userModel = new \app\api\model\DataUser();
        $this->request = $request;
    }

    /**
     * GET
     * 个人中心首页
     * @return void
     */
    public function index(){
        if($this->request->debug != 1){
            $result = [];
            $tokeninfo = $this->request->tokeninfo;
            if(empty($tokeninfo) === FALSE){
                $userInfo = $this->userModel->getOne(array(
                    'id'    => $tokeninfo['id']
                ),'id,headimg,username,nickname as nickName,phone,is_vip,is_distribution,vip_expire,vip_code,vip_name');
                if(empty($userInfo)){
                    return \Tools::returnMsg(false,array(
                        'code'  => '10004',
                        'message'=>'登录信息失效,请重新登录'
                    ),$this->default_type);
                }
                $userInfo['avatarUrl'] = $userInfo['headimg'];
                $userInfo['vip_expire'] = \Tools::getDateTimeByTime(strtotime($userInfo['vip_expire']),'Y-m-d');
                $accountModel = new \app\api\model\DataUserAccount();
                $commission = $accountModel->getOne(array(
                    'uuid'   => $tokeninfo['id']
                ),"avail_amount as `avail`,all_amount as `all`,wait_amount as `wait`,used_amount as `used`,bank_code,freeze_amount as freeze,withdraw_amount");
                if(empty($commission)){
                    $commission = array(
                        'all'   => 0,
                        'wait'  => 0,
                        'used'  => 0,
                        'avail' => 0
                    );
                }else{
                    $commission['all'] = empty($commission['all']) ? 0.00 : sprintf("%.2f",$commission['all']/100);
                    $commission['avail'] = empty($commission['avail']) ? 0.00 : sprintf("%.2f",$commission['avail']/100);
                    $commission['freeze'] = empty($commission['freeze']) ? 0.00 : sprintf("%.2f",$commission['freeze']/100);
                    $commission['withdraw_amount'] = empty($commission['withdraw_amount']) ? 0.00 : sprintf("%.2f",$commission['withdraw_amount']/100);
                    $commission['avail'] = $commission['avail'] - $commission['freeze'];
                    $commission['wait'] = empty($commission['wait']) ? 0.00 :  sprintf("%.2f",$commission['wait']/100);
                    $commission['used'] = empty($commission['used']) ? 0.00 :  sprintf("%.2f",$commission['used']/100);
                }
                //订单
                $orderModel = new \app\api\model\ShopOrder();
                $waitpay = $orderModel->getNumBystatus(array(
                    'uuid'  => $tokeninfo['id']
                ),array(
                    'payment_type'  => '0,1',
                    'status'        => '2,3'
                ));
                $wait_send = $orderModel->getNumBystatus(array(
                    'uuid'  => $tokeninfo['id'],
                    'status'=> 4
                ),array(
                    'payment_type'  => '0,1'
                ));
                $has_send = $orderModel->getNumBystatus(array(
                    'uuid'  => $tokeninfo['id']
                ),array(
                    'payment_type'  => '0,1',
                    'status'        => '5,6'
                ));
                $back = 0;
                $order = array(
                    'wait_pay'  => $waitpay,
                    'wait_send' => $wait_send,
                    'has_send'  => $has_send,
                    'back'      => $back
                );
                //判断是绑定银行卡
                $hasBank = 0;
                if(empty($commission['bank_code'])){
                    $hasBank = 1;
                }
            }else{
                $userInfo = array(
                    'id'        =>1,
                    'headimg'   => '/static/img/goods/p1.jpg',
                    'username'  =>'未登录',
                    'phone'     =>'',
                    'is_vip'    => 0,
                    'is_distribution'=>0,
                    'vip_expire'=> '',
                    'vip_code'  => '',
                    'vip_name'  => ''
                );
                $commission = array(
                    'all'   => 0,
                    'wait'  => 0,
                    'used'  => 0,
                    'avail' => 0
                );
                $order = array(
                    'wait_pay'  => 0,
                    'wait_send' => 0,
                    'has_send'  => 0,
                    'back'      => 0
                );
                $hasBank = 0;
            }
        }else{
            $result = [];
            $userInfo = array(
                'id'        =>1,
                'headimg'   => '/static/img/goods/p1.jpg',
                'username'  =>'李思',
                'phone'     =>'158****1245',
                'is_vip'    => 1,
                'is_distribution'=>0,
                'vip_expire'=> '2022-10-19',
                'vip_code'  => 'VIP1',
                'vip_name'  => '黄金会员'
            );
            $commission = array(
                'all'   => 15000.00,
                'wait'  => 100.00,
                'used'  => 400.00,
                'avail' => 1000.00
            );
            $order = array(
                'wait_pay'  => 1,
                'wait_send' => 0,
                'has_send'  => 30,
                'back'      => 0
            );
            $hasBank = 0;
        }
            $result = array(
                'userinfo'  => $userInfo,
                'commission'=> $commission,
                'order'     => $order,
                'hasbank'   => $hasBank
            );
        return \Tools::returnMsg(true,$result,$this->default_type);
    }
    /**
     * GET
     * 获取用户信息
     * @return void
     */
    public function userinfo(){
        if($this->request->debug != 1){
            $tokeninfo = $this->request->tokeninfo;
            $userInfo = [];
            if(empty($tokeninfo) === FALSE) {
                $userInfo = $this->userModel->getOne(array(
                    'id' => $tokeninfo['id']
                ), 'id,headimg as avatarUrl,nickname as nickName,username,phone,is_vip,is_distribution,vip_expire,
                vip_code,vip_name,distribution_code,has_improve_name,has_improve_avator');
                if (empty($userInfo)) {
                    return \Tools::returnMsg(false, array(
                        'code' => '10004',
                        'message' => '登录信息失效,请重新登录'
                    ), $this->default_type);
                }
                $userInfo['vip_expire'] = \Tools::getDateTimeByTime(strtotime($userInfo['vip_expire']),'Y-m-d');
            }else{
                return \Tools::returnMsg(true,[],$this->default_type);
            }
        }else{
            $userInfo = array(
                    'id'        =>1,
                    'headimg'   => '/static/img/goods/p1.jpg',
                    'username'  =>'李思',
                    'phone'     =>'15800000',
                    'is_vip'    => 0,
                    'is_distribution'=>0,
                    'vip_expire'=> '2022-11-15',
                    'vip_code'  => 'VIP1',
                    'vip_name'  => '黄金会员'
                );
        }
        return \Tools::returnMsg(true,$userInfo,$this->default_type);
    }
        /**
     * 获取openid
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getopenid()
    {
        $type = input('type', 0, 'trim,intval');
        $code = input('code', '', 'trim');
        $appid = sysconf('wx_appid');
        $secret = sysconf('wx_secret');
        $object = new \Wxchat($appid, $secret);
        $res = $object->getopenid($code, $type);
        if ($res['code'] != 1) {
            return \Tools::returnMsg(false, array(
                'code' => $res['code'],
                'message' => $res['message']
            ), $this->default_type);
        }
        return \Tools::returnMsg(true, array(
            'openid'    =>$res['openid'],
            'sessionKey'=>$res['sessionKey']
        ), $this->default_type);
    }
      /*获取access_token,不能用于获取用户信息的token*/
  public  function getAccessToken()
    {
        $appid = sysconf('wx_appid');
        $secret = sysconf('wx_secret');

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret."";

        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
        exit();
    }
    //图片合法性验证
    public function http_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, TRUE);
            curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json'
            ));
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $output = curl_exec($curl);
        curl_close($curl);

        return $output;
        exit();

    }
    //  获取手机号
    public function getPhoneNumber(){
        $tmp = $this->getAccessToken();
        $tmptoken = json_decode($tmp);
        $token = $tmptoken->access_token;
        $data['code'] = $_POST['code'];//前端获取code

        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";
        $info = $this->http_request($url,json_encode($data),'json');
        // 一定要注意转json，否则汇报47001错误
        $tmpinfo = json_decode($info);

        $code = $tmpinfo->errcode;
        $phone_info = $tmpinfo->phone_info;
        //手机号
        $phoneNumber = $phone_info->phoneNumber;
        if($code == '0'){
            return \Tools::returnMsg(true, $phoneNumber);
            die();
        }else{
            return \Tools::returnMsg(false, array(
                    'code' => '10012',
                    'message' => '请求失败'
                ));
            die();
        }

    }

    //解析手机号
    public function getphone()
    {
        $appid = sysconf('wx_appid');
        $secret = sysconf('wx_secret');
        $encryptedData = input('encryptedData', '');
        $iv = input('iv', '');
        $openid = input('openid', '');
        $sessionKey = input('sessionKey', '');
        if (isset($sessionKey) && empty($sessionKey) === FALSE) {
            $object = new \Wxchat($appid, $secret);
            if (empty($iv) || empty($encryptedData)) {
                return \Tools::returnMsg(false, array(
                    'code' => '10001',
                    'message' => '必传参数为空'
                ));
            }
            $debug = input('debug',0);
            if($debug == 1){
                $errCode = $object->getphone($sessionKey, urldecode($encryptedData), $iv);
            }else{
                $errCode = $object->getphone($sessionKey, $encryptedData, $iv);
            }

            if ($errCode['code'] == 1 && empty($errCode['data']) === FALSE) {
                return \Tools::returnMsg(true, $errCode['data']);
            } else {
                return \Tools::returnMsg(false, array(
                    'code' => '10012',
                    'message' => $errCode['code']
                ));
            }
        } else {
            return \Tools::returnMsg(false, array(
                'code' => '10012',
                'message' => '参数获取失败，请重试'
            ));
        }
    }
    /**
     * 自动登录
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function loginbyopenid(){
        $openid             = input('openid','','trim');
        $headimg            = input('headimg','https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132','trim');
        $username           = input('nickname','微信用户','trim');
        $nickname           = input('nickname','微信用户','trim');
        $mobile         = input('mobile','','trim');

        $region_province    = input('region_province','','trim');
        $region_city        = input('region_city','','trim');
        $region_area        = input('region_area','','trim');
        $base_age           = input('base_age','','trim');
        $base_sex           = input('base_sex','','trim');
        $base_birthday       = input('base_birthday','','trim');
        $channel            = input('channel',1);
        if(empty($openid)){
            return \Tools::returnMsg(false,array(
                'code'      => '10008',
                'message'   =>'参数不能为空 '
            ),$this->default_type);
        }
        $userModel = new \app\api\model\DataUser();
        $userinfo = $userModel->getOne(array(
            'openid'    => $openid
        ),'id,openid,phone,distribution_code,is_distribution,username,nickname,
        region_province,region_city,headimg,is_vip,vip_expire,has_improve_name,has_improve_avator');
        if(empty($userinfo) === FALSE){
            if(empty($username) === FALSE){
                    $data['username'] = $username;
                }
            //判断是否完善了信息
            if(empty($headimg) === FALSE && empty($userinfo['headimg'])){
                $data['headimg'] = $headimg;

            }
            if(empty($mobile) === FALSE){
                    $data['phone'] = $mobile;
                }
                if(empty($nickname) === FALSE){
                    $data['nickname'] = $nickname;
                }
                if(empty($region_province) === FALSE && empty($userinfo['region_province'])){
                    $data['region_province'] = $region_province;
                }
                if(empty($region_city) === FALSE && empty($userinfo['region_city'])){
                    $data['region_city'] = $region_city;
                }
                if(empty($region_area) === FALSE && empty($userinfo['region_area'])){
                    $data['region_area'] = $region_area;
                }
            $userModel->saveData(array(
                    'id'    => $userinfo['id']
                ),$data);
            $avatar = $userinfo['headimg'];
            unset($userinfo['headimg']);
            $accesstoken = \Tools::signJWTToken($userinfo);
            $userinfo['headimg'] = $avatar;
             //获取购物车中商品数量
            $common_cart_total = 0;
            $shopCartModel = new \app\api\model\ShopCart();
            $shopCartnum = $shopCartModel->getSum(array(
                'user_id'   => $userinfo['id']
            ),'goods_num');
            $common_cart_total = $shopCartnum;
            //未支付订单数量
            $wait_pay_num = 0;
            $orderModel = new \app\api\model\ShopOrder();
            $wait_pay_num = $orderModel->checkInNum(array(
                'uuid'  => $userinfo['id'],
                'payment_type'=>0
            ),'status','1,2,3');
            if(empty($wait_pay_num)) $wait_pay_num = 0;

            $userInfo['vip_expire'] = \Tools::getDateTimeByTime(strtotime($userinfo['vip_expire']),'Y-m-d');
            return \Tools::returnMsg(true,array(
                'accesstoken'   => $accesstoken,
                'distribution_code'     =>$userinfo['distribution_code'],
                'is_distribution'       =>$userinfo['is_distribution'],
                'id'       =>$userinfo['id'],
                'avatarUrl'               => $userinfo['headimg'],
                'username'              => $userinfo['username'],
                'nickName'              => $userinfo['nickname'],
                'name'                  => empty($userinfo['username']) ? $userinfo['nickname'] : $userinfo['username'],
                'is_vip'                =>$userinfo['is_vip'],
                'common_cart_total'     => $common_cart_total,//购物车数量
                'wait_pay_num'          => $wait_pay_num,
                'vip_expire'            => $userinfo['vip_expire'],
                'has_improve_name'      => $userinfo['has_improve_name'],
                'has_improve_avator'      => $userinfo['has_improve_avator']
            ),$this->default_type);
        }else{
            //创建用户并返回token
            $resdata = array(
                'headimg'               => $headimg,
                'username'              => $username,
                'phone'              => $mobile,
                'nickname'              => $nickname,
                'region_province'       => $region_province,
                'region_city'           => $region_city,
                'region_area'           => $region_area,
                'base_age'              => $base_age,
                'base_sex'              => $base_sex,
                'base_birthday'         => $base_birthday,
                'create_at'             =>\Tools::getDateTimeByTime(),
                'channel'               => $channel,
                'openid'                => $openid,
            );
            $res = $userModel->addData($resdata);
            $resid = $userModel->getLastID(array(
                'openid'    => $openid
            ));
            $accesstoken = \Tools::signJWTToken(array(
                'id'                    => $resid,
                'openid'                =>$openid,
                'distribution_code'     =>'',
                'is_distribution'       =>0,
                'name'                  => $nickname,
                'is_vip'                =>0,
                'vip_expire'            => ''
            ));
            return \Tools::returnMsg(true,array(
                'accesstoken'   => $accesstoken,
                'distribution_code'     =>'',
                'wait_pay_num'          => 0,
                'common_cart_total'          => 0,
                'is_distribution'       =>0,
                'name'                  => $nickname,
                'username'              => $nickname,
                'nickName'              => $nickname,
                'avatarUrl'               => 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132',
                'is_vip'                =>0,
                'vip_expire'            => ''
            ),$this->default_type);
        }
    }
    /**
     * 用户协议
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function agreement(){
        $type = input('type',1);//1用户协议   2  会员权益   3  分销规则  4 联系我们
        if($type == 1){
            $key = 'user_agreement';
        }elseif ($type == 2){
            $key = 'vip_agreement';
        }elseif ($type == 4){
            $key = 'connect_us';
        }elseif ($type == 5){
            $key = 'about_us';
        }else{
            $key = 'distribution_agreement';
        }
        $detail = sysconf($key);
        if(empty($detail)) $detail = '测试  数据为空富文本';
        return \Tools::returnMsg(true,array(
            'content'   => $detail
        ),$this->default_type);
    }

    /**
     * 登录绑定
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function bind(){
        $openid         = input('openid','','trim');
        $mobile         = input('mobile','','trim');
        $code           = input('code','','trim');
        $nickname       = input('nickname',1,'trim');//昵称
        $avatar         = input('avatar','https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132','trim');//头像
        $birthday       = input('birthday','','trim');//生日
        $base_sex       = input('base_sex','','trim');//性别
        if(empty($openid) || empty($mobile) || empty($code)){
            return \Tools::returnMsg(false,array(
                'code'      => '10008',
                'message'   =>'参数不能为空 '
            ),$this->default_type);
        }
        $tokeninfo = $this->request->tokeninfo;
        $userInfo = [];
        $userModel = new \app\api\model\DataUser();
        if(empty($tokeninfo) === FALSE) {
            $userInfo = $userModel->getOne(array(
                'id' => $tokeninfo['id']
            ), 'id,headimg,username,phone,is_vip,is_distribution,vip_expire,vip_code,vip_name,distribution_code');
            if (empty($userInfo)) {
                return \Tools::returnMsg(false, array(
                    'code' => '10004',
                    'message' => '登录信息失效,请重新登录'
                ), $this->default_type);
            }
            $messModel = new \app\api\model\DataUserMessage();
            //验证验证码是否正确
            $smsinfo = $messModel->getOne(array(
                'mobile' => $mobile,
                'msg' => $code
            ));
            if (empty($smsinfo)) {
                //验证码无效
                return \Tools::returnMsg(false, array(
                    'code' => '10031',
                    'message' => '无效的验证码'
                ), $this->default_type);
            }
            if ((time() - $smsinfo['create_at']) > 1800) {
                //过期
                return \Tools::returnMsg(false, array(
                    'code' => '10032',
                    'message' => '验证码已过期'
                ), $this->default_type);
            }
            $info = $userModel->getOne(array(
                'phone'     => $mobile
            ),'id,openid');
            if(empty($info) === FALSE && $info['openid'] != $openid){
                return  \Tools::returnMsg(false,array(
                    'code'  => '90001',
                    'message'=> '该手机号已与其他手机号绑定'
                ),$this->default_type);
            }
            $userData = array(
                'username'  => $nickname,
                'phone'     => $mobile,
                'headimg'   => $avatar,
                'base_sex'   => $base_sex,
                'base_birthday'=>$birthday
            );
            if(empty($birthday) === FALSE){
                $age = \Tools::diffBetweenTwoDays($birthday,\Tools::getDateTimeByTime());
                if($age > 0 && $age < 100){
                    $userData['base_age'] = $age;
                }
            }
            $res = $userModel->saveData(array(
                'id'    =>$tokeninfo['id']
            ),$userData);
            if($res){
                $userinfo = $userModel->getOne(array(
                    'openid'    => $openid
                ),'id,openid,distribution_code,is_distribution,username,is_vip,vip_expire');
                $accesstoken = \Tools::signJWTToken($userinfo);
                return \Tools::returnMsg(true,array(
                    'accesstoken'   => $accesstoken
                ),$this->default_type);
            }else{
                return  \Tools::returnMsg(false,array(
                    'code'  => '90002',
                    'message'=> '绑定失败，请重试'
                ),$this->default_type);
            }
        }else{
            return \Tools::returnMsg(false,array(
                    'code'  => '100001',
                    'message'=>'未登录  请先登录'
                ),$this->default_type);
        }
    }

    /**
     * 校验是否绑卡
     * @return void
     */
    public function checkBank(){
        if($this->request->debug != 1) {
            $tokeninfo = $this->request->tokeninfo;
            if (empty($tokeninfo)) {
                return \Tools::returnMsg(false, array(
                    'code' => '100001',
                    'message' => '未登录'
                ), $this->default_type);
            }
            $accountModel = new \app\api\model\DataUserAccount();
            $info = $accountModel->getOne(array(
                'uuid'  => $tokeninfo['id']
            ),'bank_code,bank_name,bank_child_name,invoice_name');
            if(empty($info) || empty($info['bank_code'])){
                return \Tools::returnMsg(true,array(
                    'has_bind'  => 0,
                    'info'  => []
                ),$this->default_type);
            }else{
                return \Tools::returnMsg(true,array(
                    'has_bind'  => 1,
                    'info'      => $info
                ),$this->default_type);
            }
        }else{
                return \Tools::returnMsg(true,array(
                    'has_bind'  => 1,
                    'info'  => array(
                        'bank_code' => '45454545',
                        'bank_name' => '建行',
                        'bank_child_name' => '大望路支行',
                        'invoice_name' => '李思',
                    )
                ),$this->default_type);
        }
    }
    /**
     * GET
     * 获取银行卡信息
     * @return void
     */
    public function bank(){
        $result = [];
        if($this->request->debug != 1){
            $tokeninfo = $this->request->tokeninfo;
            $userInfo = [];
            $banklist = [];
            $bankModel = new \app\api\model\Bank();
            $banklist = $bankModel->getAllData([],'bank_name,bank_no',[],array(
                'bank_no'   =>'asc'
            ));
            if(empty($tokeninfo) === FALSE) {
                $accountModel = new \app\api\model\DataUserAccount();
                $accountInfo = $accountModel->getOne(array(
                    'uuid'   => $tokeninfo['id']
                ),"id,bank_name,bank_child_name,bank_code,bank_b_id,invoice_name");
                $result = array(
                    'id'            => $accountInfo['id'],
                    'bank_name'     => $accountInfo['bank_name'],
                    'bank_child_name'=>$accountInfo['bank_child_name'],
                    'bank_code'     => $accountInfo['bank_code'],
                    'bank_b_id'     => $accountInfo['bank_b_id'],
                    'invoice_name'  => $accountInfo['invoice_name'],
                    'banklist'  => $banklist
                );
            }else{
                $result = array(
                    'id'            => 0,
                    'bank_name'     =>'',
                    'bank_child_name'=>'',
                    'bank_code'     => '',
                    'bank_b_id'     => '',
                    'invoice_name'  => '',
                    'banklist'  => $banklist
                );
            }
        }else{
            $result = array(
                'id'            => 1,
                'bank_name'     =>'中国建设银行',
                'bank_b_id'     => 1003,
                'bank_child_name'=>'大望路支行',
                'bank_code'     => '2342342342342342342342',
                'invoice_name'  => '李思',
                'banklist'      => array(
                    array(
                        'bank_name'     => '工商银行',
                        'bank_no'       => '1002'
                    ),
                    array(
                        'bank_name'     => '农业银行',
                        'bank_no'       => '1005'
                    ),
                    array(
                        'bank_name'     => '建设银行',
                        'bank_no'       => '1003'
                    )
                ),
            );
        }
        return \Tools::returnMsg(true,$result,$this->default_type);
    }
    /**
     * POST
     * 添加银行卡
     * @return void
     */
    public function addbank(){
        if($this->request->debug != 1){
            $tokeninfo = $this->request->tokeninfo;
            if(empty($tokeninfo) === FALSE) {
                $bank_code = input('bank_code','','trim');//银行卡号
                $bank_name = input('bank_name','','trim');//银行名称
                $bank_child_name = input('bank_child_name','','trim');//支行名称
                $invoice_name = input('invoice_name','','trim');//开户人姓名
                $bank_b_id = input('bank_b_id','','trim,intval');//银行编号
                if(empty($bank_name)){
                    return \Tools::returnMsg(false, array(
                        'code' => '10004',
                        'message' => '银行名称不能为空'
                    ), $this->default_type);
                }
                if(empty($bank_code)){
                    return \Tools::returnMsg(false, array(
                        'code' => '10004',
                        'message' => '银行卡号不能为空'
                    ), $this->default_type);
                }
                if(empty($bank_child_name)){
                    return \Tools::returnMsg(false, array(
                        'code' => '10004',
                        'message' => '支行不能为空'
                    ), $this->default_type);
                }
                if(empty($invoice_name)){
                    return \Tools::returnMsg(false, array(
                        'code' => '10004',
                        'message' => '开户人不能为空'
                    ), $this->default_type);
                }
                $accountModel = new \app\api\model\DataUserAccount();
                $accountInfo = $accountModel->getOne(array(
                    'uuid'  => $tokeninfo['id']
                ),'id');
                $data = array(
                    'bank_name'         => $bank_name,
                    'bank_child_name'   => $bank_child_name,
                    'bank_code'         => $bank_code,
                    'invoice_name'      => $invoice_name,
                    'bank_b_id'         => $bank_b_id,
                    'update_at'         => \Tools::getDateTimeByTime()
                );
                if(empty($accountInfo) === FALSE){
                    $res = $accountModel->saveData(array(
                        'id'    => $accountInfo['id']
                    ),$data);
                }else{
                    $data['create_at']  = \Tools::getDateTimeByTime();
                    $data['uuid']   = $tokeninfo['id'];
                    $res = $accountModel->addData($data);
                }
                if($res){
                    return \Tools::returnMsg(true,$res,$this->default_type);
                }else{
                     return \Tools::returnMsg(false, array(
                        'code' => '10007',
                        'message' => '添加失败'
                    ), $this->default_type);
                }
            }else{
                return \Tools::returnMsg(false, array(
                        'code' => '100001',
                        'message' => '未登录'
                    ), $this->default_type);
            }
        }else{
            return \Tools::returnMsg(true,1,$this->default_type);
        }
    }

    /**
     * PUT
     * 更新银行卡信息
     * @return void
     */
    public function updatebank(){
        if($this->request->debug != 1){
            $tokeninfo = $this->request->tokeninfo;
            if(empty($tokeninfo) === FALSE) {
                $bank_code = input('bank_code','','trim');//银行卡号
                $bank_name = input('bank_name','','trim');//银行名称
                $bank_child_name = input('bank_child_name','','trim');//支行名称
                $invoice_name = input('invoice_name','','trim');//开户人姓名
                $bank_b_id = input('bank_b_id','','trim,intval');//银行编号
                $id = input('id','','trim,intval');//账户id
                if(empty($bank_name)){
                    return \Tools::returnMsg(false, array(
                        'code' => '10004',
                        'message' => '银行名称不能为空'
                    ), $this->default_type);
                }
                if(empty($bank_code)){
                    return \Tools::returnMsg(false, array(
                        'code' => '10004',
                        'message' => '银行卡号不能为空'
                    ), $this->default_type);
                }
                if(empty($bank_child_name)){
                    return \Tools::returnMsg(false, array(
                        'code' => '10004',
                        'message' => '支行不能为空'
                    ), $this->default_type);
                }
                if(empty($invoice_name)){
                    return \Tools::returnMsg(false, array(
                        'code' => '10004',
                        'message' => '开户人不能为空'
                    ), $this->default_type);
                }
                $accountModel = new \app\api\model\DataUserAccount();
                $accountInfo = $accountModel->getOne(array(
                    'uuid'  => $tokeninfo['id'],
                    'id'  => $id
                ),'id');
                $data = array(
                    'bank_name'         => $bank_name,
                    'bank_child_name'   => $bank_child_name,
                    'bank_code'         => $bank_code,
                    'invoice_name'      => $invoice_name,
                    'bank_b_id'         => $bank_b_id,
                    'update_at'         => \Tools::getDateTimeByTime()
                );
                if(empty($accountInfo) === FALSE){
                    $res = $accountModel->saveData(array(
                        'id'    => $accountInfo['id']
                    ),$data);
                    if($res){
                        return \Tools::returnMsg(true,$res,$this->default_type);
                    }else{
                         return \Tools::returnMsg(false, array(
                            'code' => '10007',
                            'message' => '更新失败'
                        ), $this->default_type);
                    }
                }else{
                   return \Tools::returnMsg(false,array(
                        'code'  => '10004',
                        'message'=>'参数有误'
                    ),$this->default_type);
                }
            }else{
                return \Tools::returnMsg(false, array(
                        'code' => '100001',
                        'message' => '未登录'
                    ), $this->default_type);
            }
        }else{
            return \Tools::returnMsg(true,1,$this->default_type);
        }
    }


    /**
     * Notes: 更新微信的用户信息
     */
    public function setWechatInfo()
    {
        $data = $this->request->post();
            $tokeninfo = $this->request->tokeninfo;
            $post['user_id'] = $tokeninfo['id'];
        try{
            validate(SetWechatUserValidate::class)->check($data);
        }catch(ValidateException $e) {
            return \Tools::returnMsg(false, array(
                'code' => '10004',
                'message' => $e->getError()
            ), $this->default_type);
        }

        $result = UserLogic::updateWechatInfo($tokeninfo['id'], $data);
        if($result === true) {
            return \Tools::returnMsg(true,[], $this->default_type);
        }
        return \Tools::returnMsg(false,array(
            'code'  => '10014',
            'message'=>UserLogic::getError()
        ),$this->default_type);
    }

    /**
     * Notes:设置用户信息
     */
    public function setInfo()
    {
        try{
            $post = $this->request->post();
            $tokeninfo = $this->request->tokeninfo;
            $post['user_id'] = $tokeninfo['id'];
            validate(UpdateUserValidate::class)->scene('set')->check($post);
        }catch(ValidateException $e) {
            return \Tools::returnMsg(false, array(
                'code' => '10004',
                'message' => $e->getError()
            ), $this->default_type);
        }
        $result = UserLogic::setUserInfo($post);
        if($result === true) {
            return \Tools::returnMsg(true,[], $this->default_type);
        }
        return \Tools::returnMsg(false,array(
            'code'  => '10014',
            'message'=>UserLogic::getError()
        ),$this->default_type);
    }

}
